<template>
  <el-form
    :model="dataForm"
    :rules="dataRule"
    ref="dataForm"
    @keyup.enter.native="dataFormSubmit()"
    label-width="150px"
  >
    <el-form-item label="购买页图片">
      <!-- <el-input v-model="form.name" auto-complete="off"></el-input> -->
      <!--:http-request="handleRequest"-->
      <el-upload
        :limit="15"
        class="upload-demo"
        ref="upload"
        list-type="picture"
        multiple
        :action="url"
        :on-success="handleUploadImageOK"
        :on-remove="handleRemove"
        :before-upload="checkSame"
        :file-list="fileList"
        :on-change="handleChange"
        :on-exceed="overNum"
        accept="image/jpg,image/jpeg,image/png"
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->
        <div slot="tip" class="el-upload__tip">请上传1125宽度的图片，小于250KB，最多上传15张图片，待文件上传完成后可拖动顺序</div>
      </el-upload>
    </el-form-item>
    <el-form-item label="订单金额" prop="amount">
      <el-input v-model="dataForm.amount"></el-input>
    </el-form-item>
    <el-form-item label="订单金额的描述文案" prop="pageInfo">
      <el-input v-model="dataForm.pageInfo"></el-input>
    </el-form-item>
    <el-form-item label="购买页的描述文案" prop="pageDesc">
      <el-input v-model="dataForm.pageDesc"></el-input>
    </el-form-item>
    <el-form-item label="购买按钮文案" prop="buttonDesc">
      <el-input v-model="dataForm.buttonDesc"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="dataFormSubmit">确定</el-button>
      <el-button @click="init">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<style>

</style>
<script>
  import $ from 'jquery'
  export default {
    data() {
      return {
        url: '',
        dialogVisible: false,
        dialogImageUrls: '',
        fileList: [],
        dataForm: {
          imgList: []
        },
        dataRule: {
          amount: [
            {required: true, message: '订单金额不能为空', trigger: 'blur'}
          ],
          pageInfo: [
            {required: true, message: '订单金额的描述文案不能为空', trigger: 'blur'}
          ],
          pageDesc: [
            {required: true, message: '购买页的描述文案不能为空', trigger: 'blur'}
          ],
          buttonDesc: [
            {required: true, message: '购买按钮文案不能为空', trigger: 'blur'}
          ]
        },
      }
    },
    mounted() {
      this.url = this.$http.adornUrl(
        `/operate/bugPageInfo/upload?token=${this.$cookie.get('token')}`
      )
      this.init()
    },
    updated() {
      const liList = document.querySelectorAll('.el-upload-list__item')
      const that = this;
      window.dragElement = null;
      liList.forEach((item, index) => {
        item.setAttribute('draggable', true)
        item.ondragstart = (e) => {
          // 记录的拖动节点
          window.dragElement = item
          e.dataTransfer.setData('text/html', item.innerHTML)
          e.dataTransfer.setData('textIndex', index)
        }
        item.ondragover = (e) => {
          // 不执行无法进入drop事件
          e.preventDefault()
        }
        item.ondrop = () => {
          if (window.dragElement !== item) {
            const nIndex = +$(item).index()
            // 被插入的节点交换元素值
            const dragIndex = +$(window.dragElement).index()
            const dragFormItem = that.dataForm.imgList[dragIndex]
            const fileListItem = that.fileList[dragIndex]
            // 移除数组的
            that.dataForm.imgList.splice(dragIndex, 1)
            that.fileList.splice(dragIndex, 1)
            that.dataForm.imgList.splice(nIndex, 0, dragFormItem)
            that.fileList.splice(nIndex, 0, fileListItem)
          }
          // const a = that.groupForm.qrCodeImages.map(qrItem => qrItem.imageName);
          // console.log('TCL: item.ondrop -> a', a);
          // console.log('flistlist', this.fileList);
        };
      });
    },
    methods: {
      init() {
        this.fileList = []
        this.$http({
          url: this.$http.adornUrl(
            `/operate/bugPageInfo/info`
          ),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataForm = data.shareInfo
            data.shareInfo.imgList.map((item) => {
              this.fileList.push({url: item})
            })
          }
        })
      },
      handleUploadImageOK(res, file, fileList) {
        const that = this;
        fileList.map((item, index) => {
          if (item.name === file.name) {
            that.dataForm.imgList[index] = res.url
          }
          return true;
        });
        this.fileList = fileList
      },
      // 移除图片id
      handleRemove(file, fileList) {
        console.log(file)
        if (file.response) {
          const newImageList =
            this.dataForm.imgList.filter(item => (item !== file.response.url))
          this.dataForm.imgList = newImageList
          this.fileList = fileList
        } else {
          const newImageList =
            this.dataForm.imgList.filter(item => (item !== file.url))
          this.dataForm.imgList = newImageList
          this.fileList = fileList
        }
        // const a = this.groupForm.qrCodeImages.map(qrItem => qrItem.imageName);
        // console.log('remove -> a', a);
      },
      checkSame(file) {
        const that = this
        for (let i = 0; i < that.fileList.length; i += 1) {
          if (that.fileList[i].name === file.name) {
            that.$message.error('禁止上传相同的图片');
            return false
          }
        }
        const is250K = file.size / 1024 < 250
        if (!is250K) {
          this.$message.error('上传的图片要小于250KB!')
        }
        const isSize = new Promise(function(resolve, reject) {
          let width = 1125
          let _URL = window.URL || window.webkitURL
          let img = new Image()
          img.onload = function() {
            let valid = img.width == width
            valid ? resolve() : reject()
          }
          img.src = _URL.createObjectURL(file)
        }).then(
          () => {
            return file
          },
          () => {
            this.$message.error('上传的图片宽度必须是1125!')
            return reject()
          }
        )
        return is250K && isSize
      },
      overNum() {
        this.$message.error('最多上传15张图片!')
      },
      handleChange(file, fileList) {
        this.loading = true
        if (fileList.length > 0) this.localFileList = fileList;
        console.log('​handleChange -> his.localFileList', this.localFileList.length);
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            console.log(this.dataForm)
            this.$http({
              url: this.$http.adornUrl(
                `/operate/bugPageInfo/update`
              ),
              method: 'post',
              data: this.$http.adornData(this.dataForm)
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500
                });
              } else {
                this.$message.error(data.msg)
              }
            });
          }
        });
      }
    }
  }
</script>
